package com.kewu.system.job;

import com.kewu.common.cons.sys.BeanConstants;
import com.kewu.common.util.CronUtil;
import com.kewu.common.util.SpringContextUtil;
import com.kewu.system.api.cons.QuartzConstants;
import com.kewu.system.api.entity.SysQuartz;
import com.kewu.system.api.enums.JobPolicyEnum;
import com.kewu.system.api.enums.QuartzStatusEnum;
import com.kewu.system.dao.SysQuartzDao;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;

/**
 * @author wangning
 * @create 2024-05-29-11:08
 */
@Slf4j
public class QuartzJob implements Job {
    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        SysQuartz sysQuartz = (SysQuartz) context.getJobDetail().getJobDataMap().get(QuartzConstants.QUARTZ_KEY);
        log.info("任务执行，【{}】", new SimpleDateFormat(CronUtil.YYYY_MM_DD).format(new Date()));
        // 如果执行策略是只执行一次，则需要修改执行状态
        if (JobPolicyEnum.EXECUTE_ONCE.getCode().equals(sysQuartz.getMisfirePolicy())) {
            sysQuartz.setStatus(QuartzStatusEnum.STARTED.getCode());
            SysQuartzDao sysQuartzDao = (SysQuartzDao) SpringContextUtil.getBean(BeanConstants.SYS_QUARTZ_DAO);
            if (Objects.nonNull(sysQuartzDao)) {
                sysQuartzDao.update(sysQuartz);
                log.info("任务状态修改:【{}】", sysQuartz.getId());
                return;
            }
            log.warn("修改失败，Bean不存在【sysQuartzDao】");
        }
    }
}
